package pers.zhouyoudianxi.notice2.config;

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.concurrent.ThreadFactory;

@Configurable
public class SchedulerConfig {
    @Bean
    public ThreadPoolTaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(5); // 线程池大小
        scheduler.setThreadNamePrefix("task-scheduler-"); // 线程名前缀
        scheduler.setWaitForTasksToCompleteOnShutdown(true); // 关闭时等待任务完成
        scheduler.setAwaitTerminationSeconds(60); // 等待终止的时间
        return scheduler;
    }


    /**
     * 自定义任务调度器，解决线程环境冲突
     */
    @Bean
    public TaskScheduler taskSchedulerSwing() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(1);
        scheduler.setThreadNamePrefix("swing-scheduler-");

        // 关键配置：设置非守护线程，避免窗口被强制关闭
        scheduler.setThreadFactory(new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setDaemon(false); // 非守护线程
                thread.setPriority(Thread.NORM_PRIORITY);
                return thread;
            }
        });

        scheduler.initialize();
        return scheduler;
    }
}
